//定义蛇的类
class Snake{
    //蛇的容器
    element:HTMLElement;
    //蛇的头部
    head:HTMLElement;
    //蛇的身体
    bodies:HTMLCollection
    constructor(){
        this.element = document.getElementById('snake')!;
        this.head = document.querySelector('#snake >div') as HTMLElement;
        this.bodies =this.element.getElementsByTagName('div');
    }
    //蛇头坐标
    get X(){
        return this.head.offsetLeft;
    } 
    get Y(){
        return this.head.offsetTop;
    }
    set X(value:number){
        //新值和旧值相同就不改了
       if (this.X === value) {
            return;
       }
       //X值的范围
       if (value < 0 || value > 290) {
        //进入判断说明蛇撞墙了
        throw new Error("蛇撞墙了！");
        
       }
       //修改X时，是在修改X坐标。蛇的身体多了后蛇向右移动不能向左掉头
       if (this.bodies[1]&&(this.bodies[1] as HTMLElement).offsetLeft === value) {
            //如果发生了掉头，那就反方向继续移动
            if (value > this.X) {
                //新的值 大于旧的X 蛇旧继续向左走
                value = this.X - 10;
                
            }else{
                value = this.X + 10;
            }
       }
       
       
       
       //移动身体
       this.moveBody();
    
       this.head.style.left = value + 'px';
       
    //    this.checkIsEatBody();
    } 
    set Y(value:number){
        if (this.Y === value) {
            return;    
        }   
        //Y值的范围
       if (value < 0 || value > 290) {
        //进入判断说明蛇撞墙了
        throw new Error("蛇撞墙了！");
        
       }
       if (this.bodies[1]&&(this.bodies[1] as HTMLElement).offsetTop === value) {
        //如果发生了掉头，那就反方向继续移动
        if (value > this.Y) {
            //新的值 大于旧的X 蛇旧继续向左走
            value = this.Y - 10;
            
        }else{
            value = this.Y + 10;
        }
   }
      
        //移动身体
        this.moveBody(); 
        
       this.head.style.top = value + 'px';

    //    this.checkIsEatBody();
       
    }

    //蛇增加身体
    addBody(){
        this.element.insertAdjacentHTML('beforeend','<div></div>')
    }
    //蛇的身体移动的方法
    moveBody(){
        /**
         * 将后边身体设置为前边身体的位置
         */
        for(let i = this.bodies.length-1;i>0;i--){
            //获取前边身体的位置
            let X = (this.bodies[i-1] as HTMLElement).offsetLeft;
            let Y = (this.bodies[i-1] as HTMLElement).offsetTop;
            //设置到身体上
            (this.bodies[i] as HTMLElement).style.left = X +'px';
            (this.bodies[i] as HTMLElement).style.top = Y +'px';
        }
        
    }
    checkIsEatBody(){
        for (let i = 0; i < this.bodies.length; i++) {
            let bd = this.bodies[i] as HTMLElement;
            if (this.X === bd.offsetLeft && this.Y === bd.offsetTop) {
                //蛇头撞到了身体
                throw new Error("蛇头撞到了身体！");
                
            }
            
        }
    }
}

export default Snake;